package com.hnjfzn.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnjfzn.common.core.utils.StringUtils;
import com.hnjfzn.common.core.utils.uuid.IdUtils;
import com.hnjfzn.common.security.utils.SysUtils;
import com.hnjfzn.system.api.domain.SysInfo;
import com.hnjfzn.system.domain.vo.SysVo;
import com.hnjfzn.system.mapper.SysInfoMapper;
import com.hnjfzn.system.service.ISysInfoService;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysInfoServiceImpl extends ServiceImpl<SysInfoMapper, SysInfo> implements ISysInfoService {
    /**
     * 项目启动时，初始化到缓存
     */
    @PostConstruct
    public void init() {
        refreshRedis();
    }

    @Override
    public void reset() {
        SysUtils.clear();
        refreshRedis();
    }

    @Override
    public List<SysVo> sys(String type) {
        List<SysInfo> list = refreshRedis();
        if (null != list && !list.isEmpty()) {
            return list.stream().filter(item -> {
                // 条件过滤
                if (item.getStatus().equals("0")){
                    return StringUtils.isEmpty(type) || item.getSysType().equals(type);
                }
                return false;
            }).map(item -> new SysVo(item.getSysId(), item.getSysLogo(), item.getSysCode(), item.getSysName(), item.getRemark(), item.getIsThird().equals("0"))).collect(Collectors.toList());
        }
        return List.of();
    }

    @Override
    public Map<String, Object> all() {
        List<SysInfo> list = refreshRedis();
        if (list != null && !list.isEmpty()) {
            return list.stream().collect(Collectors.toMap(SysInfo::getSysCode, SysInfo::getSysId));
        }
        return Map.of();
    }

    @Override
    public Map<String, Object> selectSysPermsByUserId(Long userId) {
        List<SysInfo> sysInfos = baseMapper.selectSysPermsByUserId(userId);
        if (sysInfos != null && !sysInfos.isEmpty()) {
            return sysInfos.stream().collect(Collectors.toMap(SysInfo::getSysCode, SysInfo::getSysId));
        }
        return Map.of();
    }

    @Override
    public List<SysInfo> list() {
        return refreshRedis();
    }

    @Override
    public boolean save(SysInfo entity) {
        do {
            // 创建并检查 sysCode 是否存在
            entity.setSysCode(IdUtils.fastSimpleUUID());
        } while (super.exists(new LambdaQueryWrapper<SysInfo>().eq(SysInfo::getSysCode, entity.getSysCode())));

        // 保存
        boolean flag = super.save(entity);
        if (flag) {
            SysUtils.set(entity.getSysCode(), entity);
        }
        return flag;
    }

    @Override
    public boolean updateById(SysInfo entity) {
        boolean flag = super.updateById(entity);
        if (flag) {
            SysUtils.remove(entity.getSysCode());
            SysUtils.set(entity.getSysCode(), entity);
        }
        return flag;
    }

    /**
     * 刷新
     */
    private static boolean REFRESH_FLAG = false;

    /**
     * 刷新缓存
     *
     * @return 系统信息
     */
    private List<SysInfo> refreshRedis() {
        // 缓存中获取平台信息
        List<SysInfo> list = SysUtils.getAll();
        if (null != list && !list.isEmpty()) {
            return list;
        } else {
            try {
                if (!REFRESH_FLAG) {
                    REFRESH_FLAG = true;
                    // 获取列表
                    list = super.list();
                    // 放入缓存中
                    list.forEach(item -> SysUtils.set(item.getSysCode(), item));
                }
            } finally {
                REFRESH_FLAG = false;
            }
        }

        return list;
    }
}
